#!/usr/bin/env python
from distutils.core import setup
import py2exe, os, zipfile, re
 
setup(console=['BrownieHelper.py'])

#Utilities
path = os.getcwd()
rootPath = os.path.split(path)[0]

print "Working path: ", path
print "Root path: ", rootPath

def copyFile(sourcePath,destinationPath):
    fr = open(sourcePath,'rb')
    fw = open(destinationPath,'wb')
    fw.write(fr.read())
    fr.close()
    fw.close()
    
def deleteDir(path):
    for root, dirs, files in os.walk(path, topdown=False):
        for name in files:
            os.remove(os.path.join(root, name))
        for name in dirs:
            os.rmdir(os.path.join(root, name))
    os.rmdir(path)
    
def makeZip(sourcePath, destinationPath, rootFilter=lambda name: True, fileFilter=lambda name: not name.endswith(".zip")):
    
    fz = zipfile.ZipFile(destinationPath,'w')
    
    for root, dirs, files in os.walk(sourcePath):
        if rootFilter(root):
            for file in files:
                file_path = os.path.join(root, file)
                if fileFilter(file): fz.write(file_path,"BrownieHelper\\"+file_path[len(sourcePath):])
            
    fz.close()

def getVersionNumber():
    
    fs = open(os.path.join(rootPath,"BrownieHelper.toc"))
    tocTxt = fs.read()
    fs.close()

    match = re.search(r'##\s*Version:\s*(?P<version>.*?)\s*\n',tocTxt)
    if match: return match.groupdict()['version']
    else: return "0.0"


#Once we do our setup fix up the folder structure
print "Moving dist files to script root..."
for f in os.listdir(os.path.join(path, "dist")): copyFile(os.path.join(path,"dist",f),os.path.join(path,f))

print "Removing dist and build directories..."
deleteDir(os.path.join(path,"dist"))
deleteDir(os.path.join(path,"build"))

scriptDestination = os.path.join(path,"BrownieHelper_"+getVersionNumber()+"_script.zip")
print "Building archive with script: ", scriptDestination
makeZip(rootPath,scriptDestination)

noscriptDestination = os.path.join(path,"BrownieHelper_"+getVersionNumber()+"_noscript.zip")
print "Building archive with script: ", noscriptDestination
makeZip(rootPath,noscriptDestination,lambda name: "script" not in name)

print "Done."